import BaseButton from '@/components/base/BaseButton';
import BaseModal, { ModalFC, useModal } from '@/components/base/BaseModal';
import BaseTable from '@/components/base/BaseTable';
import BaseTree from '@/components/base/BaseTree';
import { EnableStatusEnum } from '@/models';
import { useRequest } from '@/utils/request';
import { BlockOutlined } from '@ant-design/icons';
import { ActionType } from '@ant-design/pro-table';
import { Col, Row, Spin, Tag } from 'antd';
import { useMemo, useRef, useState } from 'react';
import { RadarTreeItem, RadarTreeTypeEnum } from '../../data';
import { getList as getKeyPartsModelList } from '../../keyParts/KeyPartsModelInfo/api';
import { getList as getExtensionList } from '../../SubExtensionInfo/api';
import { getList as getSystemList } from '../../SubSystemInfo/api';
import { getKeyPartsList, getRadarTreeListByRadarId } from '../api';
import EnsurePlanInfo from './components/EnsurePlanInfo';
import EditStructureModal from './EditStructureModal';
import KeyPartsSelectModal from './KeyPartsSelectModal';

interface TreeItem {
  treeId: string;
  id: string;
  type: number;
  children?: TreeItem[];
}
const getIds = (findId: string, list: TreeItem[], type: number): string[] => {
  for (let i = 0; i < list.length; i += 1) {
    const item = list[i];
    if (type > item.type) {
      if (item.children) {
        const ids = getIds(findId, item.children, type);
        if (ids.length > 0) {
          ids.unshift(item.id);
          return ids;
        }
      }
    } else if (type === item.type) {
      if (item.id === findId) {
        return [findId];
      }
    }
  }
  return [];
};
const StructureModal: ModalFC<{ id: string; areaId: string; name: string }> = ({
  id: radarId,
  areaId,
  name,
  ...props
}) => {
  const radarTree = useRequest(getRadarTreeListByRadarId, {
    defaultParams: [radarId],
    initialData: []
  });
  const [activeItem, setActiveItem] = useState<RadarTreeItem>(() => ({
    id: radarId,
    name,
    treeId: '',
    type: RadarTreeTypeEnum.enum.radar
  }));
  const useTableRef = useRef<Record<string, ActionType>>({});
  const keyPartsSelectModal = useModal(KeyPartsSelectModal, {
    onSuccess() {
      useTableRef.current[activeItem.type]?.reload();
    }
  });
  const editStructureModal = useModal(EditStructureModal, {
    onSuccess() {
      radarTree.run(radarId);
      setActiveItem({
        id: radarId,
        name,
        treeId: '',
        type: RadarTreeTypeEnum.enum.radar
      });
      useTableRef.current[RadarTreeTypeEnum.enum.radar]?.reload();
    }
  });
  const showList = useMemo(() => {
    const { id, name, type } = activeItem;
    if (type === RadarTreeTypeEnum.enum.radar) {
      return (
        <>
          <BaseTable
            key='system'
            rowKey='id'
            actionRef={(actionRef) => {
              useTableRef.current[RadarTreeTypeEnum.enum.radar] = actionRef;
            }}
            headerTitle={`${name} 分系统列表`}
            request={getSystemList}
            height={200}
            params={{ radarId: id }}
            columns={[
              { dataIndex: 'name', title: '分系统' },
              { dataIndex: 'remarks', title: '备注' }
            ]}
          />
        </>
      );
    }
    if (type === RadarTreeTypeEnum.enum.system) {
      return (
        <BaseTable
          key='extension'
          rowKey='id'
          actionRef={(actionRef) => {
            useTableRef.current[RadarTreeTypeEnum.enum.system] = actionRef;
          }}
          headerTitle={`${name} 分机列表`}
          height={200}
          params={{ systemId: id, radarId }}
          request={getExtensionList}
          columns={[
            { dataIndex: 'name', title: '分机' },
            { dataIndex: 'remarks', title: '备注' }
          ]}
        />
      );
    }
    if (type === RadarTreeTypeEnum.enum.extension) {
      return (
        <BaseTable
          key='keyPartsType'
          rowKey='id'
          actionRef={(actionRef) => {
            useTableRef.current[RadarTreeTypeEnum.enum.extension] = actionRef;
          }}
          headerTitle={`${name} 关重件型号列表`}
          height={200}
          params={{ extensionId: id, radarId }}
          request={getKeyPartsModelList}
          columns={[
            { dataIndex: 'name', title: '关重件' },
            { dataIndex: 'remarks', title: '备注' }
          ]}
        />
      );
    }
    if (type === RadarTreeTypeEnum.enum.keyParts) {
      return (
        <BaseTable
          key='keyParts'
          actionRef={(actionRef) => {
            useTableRef.current[RadarTreeTypeEnum.enum.keyParts] = actionRef;
          }}
          rowKey='id'
          height={200}
          params={{ radarId, modelId: id }}
          request={getKeyPartsList}
          headerTitle={`${name}关重件 设备记录`}
          toolBarRender={() => [
            <BaseButton
              type='primary'
              code='switchKeyParts'
              onClick={() => {
                keyPartsSelectModal.load({ radarId, areaId, modelId: id });
              }}
            >
              设备切换
            </BaseButton>
          ]}
          columns={[
            { title: '启用时间', dataIndex: 'startUseTime', valueType: 'date' },
            {
              title: '启用状态',
              dataIndex: 'isUse',
              render(text, record) {
                const t = EnableStatusEnum.getLabelByValue(record.isUse);
                const color = record.isUse ? 'success' : 'default';
                return <Tag color={color}>{t}</Tag>;
              }
            }
          ]}
        />
      );
    }
    return null;
  }, [radarId, activeItem, keyPartsSelectModal]);
  const planInfo = useMemo(() => {
    const { id, name, type, treeId } = activeItem;
    const [, raSystemId, raExtensionId, keyPartsModelId] = getIds(id, radarTree.data, type);
    return (
      type !== RadarTreeTypeEnum.enum.radar && (
        <EnsurePlanInfo
          title={name}
          structureId={treeId}
          raSystemId={raSystemId}
          raExtensionId={raExtensionId}
          keyPartsModelId={keyPartsModelId}
        />
      )
    );
  }, [activeItem]);
  return (
    <BaseModal footer={false} title='雷达结构树管理' width={1200} {...props}>
      <Row gutter={8}>
        <Col span={9}>
          <Spin spinning={radarTree.loading}>
            <BaseButton
              type='primary'
              code='editStructure'
              style={{ marginBottom: 8 }}
              icon={<BlockOutlined />}
              onClick={() => {
                editStructureModal.load({ id: radarId });
              }}
            >
              编辑结构树
            </BaseButton>
            <BaseTree
              treeData={radarTree.data}
              bindProps={{ key: 'treeId', value: 'treeId', title: 'name' }}
              blockNode
              height={240}
              defaultExpandAll
              selectedKeys={[activeItem.treeId]}
              onSelect={(keys, { node }) => {
                setActiveItem(node as unknown as RadarTreeItem);
              }}
              titleRender={(nodedata) => {
                return (
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span>{nodedata.title}</span>
                    <span>{/* {RadarTreeTypeEnum.getLabelByValue(nodedata.type)} */}</span>
                  </div>
                );
              }}
            />
          </Spin>
        </Col>
        <Col span={15}>{showList}</Col>
      </Row>
      {planInfo}
    </BaseModal>
  );
};

export default StructureModal;
